<?php 
/**
 * Класс, который реализовует локализацию
 *
 */

class FRM_Db_Localized_Abstract extends FRM_Db_Table
{
	/**
	 * Название локализиваной таблицы
	 *
	 * @var string
	 */
	protected $localizedTable = null;

	/**
	 * Перечень локализованій полей 
	 * $key => $value понимается как `$key` as `$value`
	 *
	 * @var array
	 */
	protected $localizedFields = null;

	/**
	 * Ключевое поле для локализованой таблицы
	 *
	 * @var string
	 */
	protected $localizedKeyField = 'id';

	/**
	 * Языковое поле для локализованой таблицы
	 *
	 * @var string 
	 */
	protected $langField = 'lang';

	/**
	 * Текущий язык
	 *
	 * @var string
	 */
	protected $actualLang;

	/**
	 * Язык по умолчанию
	 *
	 * @var string
	 */
	protected $defaultLang;
	
	/**
	 * Avaible languages
	 *
	 * @var array
	 */
	protected $langs = array();

	/**
	 * Enter description here...
	 *
	 */
	
	public function setActualLang($actualLang){
		$this->actualLang = $actualLang;
		return $this;
	}
	
	public function getActualLang(){
		return $this->actualLang;
	}
	
	public function getLocalizedFields(){
		return $this->localizedFields;
	}
	
	public function getLangs(){
		return $this->langs;
	}
	
	public function init()
	{
		if(!is_null($this->_name)){
			if(is_null($this->localizedTable)){
				$this->localizedTable = $this->_name.'_localization';
			}

		}
		
		if(is_array($this->localizedFields) && count($this->localizedFields)){
			if(is_null($this->currentSelect)){
				$this->currentSelect = new FRM_Db_Select_Abstract($this->getAdapter());
				$this->currentSelect->from($this->_name);
			}
			
			$cols = array();
			foreach ($this->localizedFields as $k=>$v){
				$cols[] = "IF(l1.`$v` is not null and l1.`$v`!='', l1.`$v`, l2.`$v`) as $k";
			}
			
			$this->currentSelect->joinLeft(array('l1'=>$this->localizedTable),
			"`$this->_name`.`{$this->keyField}`=`l1`.`{$this->localizedKeyField}` && l1.`{$this->langField}`='{$this->actualLang}'", $cols);
			$this->currentSelect->joinLeft(array('l2'=>$this->localizedTable),
			"`$this->_name`.`{$this->keyField}`=`l2`.`{$this->localizedKeyField}` && l2.`{$this->langField}`='{$this->defaultLang}'", array());
			
			$this->formRelations['t_localization']=array("className"=>'FRM_Db_Table_Localizaton', "parram"=>$this->_name, "key"=>"lang");
		}
		
		//print_r($this->formRelations);
		
		parent::init();
	}
}
